from flask import Flask,request, jsonify, render_template,redirect, url_for, session
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import or_, and_
from functools import wraps
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:GNSS%40ccyy123@localhost/blind_dates'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
app.secret_key = 'xiangqinjiemu520'   # 用于加密 session，必须设置！
###设置数据库###
class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    number = db.Column(db.String(64), nullable=False)
    name = db.Column(db.String(64), nullable=False)
    gender = db.Column(db.String(16), nullable=False)
    worker = db.Column(db.String(128), nullable=False)
    identity = db.Column(db.String(128), default='用户')
    voted_id = db.Column(db.String(36), nullable=True)  # 表示投给了谁（只能投一次）
class Match(db.Model):
    __tablename__ = 'matches'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user1_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    user2_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    user1 = db.relationship('User', foreign_keys=[user1_id])
    user2 = db.relationship('User', foreign_keys=[user2_id])
#注册接口
@app.route('/register', methods=['POST'])
def register():
    data = request.json
    required_fields = ['number', 'name', 'gender', 'worker']
    if not all(field in data for field in required_fields):
        return jsonify({'error': '请填写完所有信息'}), 400
    user = User(
        number=data['number'],
        name=data['name'],
        gender=data['gender'],
        worker=data['worker'],
    )
    db.session.add(user)
    db.session.commit()
    return jsonify({'message': 'User registered', 'user_id': user.id}), 201
#登录接口
@app.route('/login', methods=['POST'])
def login():
    data = request.json
    user = User.query.filter_by(number=data['number'], name=data['name']).first()

    if not user:
        return jsonify({'error': '用户名或密码错误'}), 401

    # 存入 session
    session['user_id'] = user.id
    session['identity'] = user.identity

    return jsonify({
        'user_id': user.id,
        'identity': user.identity
    }), 200
def login_required(view_func):
    @wraps(view_func)
    def wrapper(*args, **kwargs):
        if 'user_id' not in session:
            return redirect(url_for('login_page'))
        return view_func(*args, **kwargs)
    return wrapper
#投票接口
@app.route('/vote', methods=['POST'])
@login_required
def vote():
    data = request.json

    # 获取投票人和被投票人
    voter_id = data.get('voter_id')
    target_id = data.get('target_id')

    voter = User.query.get(voter_id)
    target = User.query.get(target_id)

    # 校验基本条件
    if not voter or not target:
        return jsonify({'error': '用户不存在'}), 404
    if voter.voted_id:
        return jsonify({'error': '您已经投过票，不能重复投票'}), 400
    if voter.id == target.id:
        return jsonify({'error': '不能投给自己'}), 400
        # 禁止已匹配者再次投票
    already_matched = Match.query.filter(
        db.or_(Match.user1_id == voter.id, Match.user2_id == voter.id)
    ).first()
    if already_matched:
        return jsonify({'error': '您已经匹配成功，不能再投票'}), 400
    if voter.gender == target.gender:
        return jsonify({'error': '不能投给同性用户'}), 400
    # 更新投票状态
    voter.voted_id = target.id
    db.session.commit()

    return jsonify({'message': '投票成功'}), 200
@app.route('/match/scan', methods=['GET'])
def scan_matches():
    users = User.query.all()
    matched = []

    for user in users:
        if not user.voted_id:
            continue

        target = User.query.get(int(user.voted_id))
        if not target:
            continue

        # 检查是否互投
        if target.voted_id and int(target.voted_id) == user.id:
            # 检查是否已经匹配过
            existing = Match.query.filter(
                or_(
                    and_(Match.user1_id == user.id, Match.user2_id == target.id),
                    and_(Match.user1_id == target.id, Match.user2_id == user.id)
                )
            ).first()

            if not existing:
                match = Match(user1_id=user.id, user2_id=target.id)
                db.session.add(match)
                matched.append({
                    "user1": {"id": user.id, "name": user.name},
                    "user2": {"id": target.id, "name": target.name}
                })

    db.session.commit()

    return jsonify({
        "message": f"成功匹配 {len(matched)} 对用户",
        "matches": matched
    }), 200
@app.route('/screen_votes_only')
@login_required
def screen_votes_only():
    users = User.query.all()
    total_votes = sum(1 for u in users if u.voted_id)

    # 用于记录已处理过的用户 ID 对（避免重复显示）
    matched_pairs = []
    matched = []

    for user in users:
        if not user.voted_id:
            continue

        try:
            target_id = int(user.voted_id)
        except:
            continue

        target = User.query.get(target_id)
        if not target or not target.voted_id:
            continue

        # 判断是否互投
        if int(target.voted_id) == user.id:
            pair = tuple(sorted([user.id, target.id]))
            if pair not in matched_pairs:
                matched_pairs.append(pair)
                matched.append({
                    'user1': user,
                    'user2': target
                })

    return render_template('screen.html',
                           total_votes=total_votes,
                           matches=matched)

@app.route('/users', methods=['GET'])
def get_users():
    users = User.query.all()
    user_list = []
    for u in users:
        user_list.append({
            'id': u.id,
            'number': u.number,
            'name': u.name,
            'gender': u.gender,
            'worker': u.worker,
            'voted_id': u.voted_id
        })
    return jsonify(user_list)
@app.route('/screen_votes_only/data')
def get_matches_json():
    users = User.query.all()
    matched_pairs = []
    matched = []

    for user in users:
        if not user.voted_id:
            continue
        try:
            target_id = int(user.voted_id)
        except:
            continue
        target = User.query.get(target_id)
        if not target or not target.voted_id:
            continue
        if int(target.voted_id) == user.id:
            pair = tuple(sorted([user.id, target.id]))
            if pair not in matched_pairs:
                matched_pairs.append(pair)
                matched.append({
                    'user1': user.name,
                    'user2': target.name
                })

    total_votes = sum(1 for u in users if u.voted_id)

    return jsonify({
        'matches': matched,
        'total_votes': total_votes,
        'match_count': len(matched)
    })

@app.route('/')
def login_page():
    return render_template('login.html')

@app.route('/register_page')
def register_page():
    return render_template('register.html')
@app.route('/vote_ui')
@login_required
def vote_ui():
    return render_template('vote_ui.html')
if __name__ == '__main__':
   #app.run(debug=True)
   app.run(host='192.168.0.100', port=5000)
